package com.xihuanjun.healthcode.controller;

import com.xihuanjun.healthcode.entity.User;
import com.xihuanjun.healthcode.entity.dto.UserDTO;
import com.xihuanjun.healthcode.entity.vo.UserVO;
import com.xihuanjun.healthcode.exception.ServiceException;
import com.xihuanjun.healthcode.service.UserService;
import com.xihuanjun.util.JWTUtils;
import com.xihuanjun.util.MapUtils;
import com.xihuanjun.util.ValidateUtils;
import com.xihuanjun.util.json.JsonResult;
import com.xihuanjun.validate.enums.ValidateType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 江溪浣
 * @createDate: 2022/10/25 10:32
 * @description:
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    JWTUtils jwtUtils;

    @PostMapping("/login")
    public JsonResult login(@RequestBody Map map){
        String loginName = MapUtils.getString(map, "loginName");
        String pwd = MapUtils.getString(map, "pwd");
        if(StringUtils.hasText(loginName)==false ||
        StringUtils.hasText(pwd)==false){
            throw new ServiceException("用户名和密码不能为空");
        }
        //用户信息
        UserVO login = userService.login(loginName, pwd);
        //token信息
        Map<String,String> tokenData=new HashMap<>();
        tokenData.put("userid",login.getId().toString());
        Map<String, String> tokenMap = jwtUtils.generateUserToken(tokenData);

        return new JsonResult().code(200).data(JsonResult.KEY_ITEM,login).map(tokenMap);
    }

    @PostMapping("/update/info")
    public JsonResult updateInfo(@RequestBody UserDTO userDTO, HttpServletRequest request){
        userDTO.setId(Long.parseLong(jwtUtils.getTokenValue(request,"userid")));
        userService.updateInfo(userDTO);
        return new JsonResult().code(200).msg("修改成功");
    }

    @PostMapping("/update/pwd")
    public JsonResult updatePwd(@RequestBody Map map,HttpServletRequest request){
        String oldPwd = MapUtils.getString(map, "oldPwd");
        String newPwd = MapUtils.getString(map, "newPwd");
        String userid = jwtUtils.getTokenValue(request, "userid");
        boolean b = userService.updatePwd(Long.parseLong(userid), oldPwd, newPwd);
        return new JsonResult().code(200).msg("修改成功");
    }

    @GetMapping("/subordinate")
    public JsonResult subordinate(){
        List<UserVO> subordinate = userService.subordinate();
        return new JsonResult().code(200).data(JsonResult.KEY_ITEMS,subordinate);
    }

}
